package com.cruise.game.controller;

import com.cruise.game.common.api.ApiException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RestController;

/**
 * 基础控制器
 *
 * @author cruise
 * @date 2025-02-28
 */
@RestController
public class BaseController {

    /**
     * 获取当前用户ID
     *
     * @return 用户ID
     */
    protected Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && authentication.getPrincipal() != null) {
            // 进行安全的类型转换
            Object principal = authentication.getPrincipal();
            if (principal instanceof Long) {
                return (Long) principal;
            } else if (principal instanceof String) {
                try {
                    return Long.valueOf(principal.toString());
                } catch (NumberFormatException e) {
                    throw new ApiException("无效的用户ID");
                }
            }
        }
        throw new ApiException("用户未登录");
    }

    /**
     * 获取当前认证信息
     *
     * @return 认证信息
     */
    protected Authentication getCurrentAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication;
        }
        throw new ApiException("用户未登录");
    }

    /**
     * 获取当前用户角色
     *
     * @return 用户角色
     */
    protected String getCurrentUserRole() {
        Authentication authentication = getCurrentAuthentication();
        return authentication.getAuthorities().stream()
                .findFirst()
                .map(authority -> authority.getAuthority().replace("ROLE_", ""))
                .orElse(null);
    }

    /**
     * 验证当前用户是否是管理员
     *
     * @return 是否是管理员
     */
    protected boolean isAdmin() {
        String role = getCurrentUserRole();
        return "admin".equalsIgnoreCase(role);
    }

    /**
     * 验证当前用户是否是代理
     *
     * @return 是否是代理
     */
    protected boolean isAgent() {
        String role = getCurrentUserRole();
        return "agent".equalsIgnoreCase(role) || "admin".equalsIgnoreCase(role);
    }
}